<template>
  <div class="hospital-list-container">
    <!-- 搜索筛选区域 -->
    <div class="search-section">
      <el-card shadow="hover">
        <div class="search-form">
          <!-- 医院名称搜索 -->
          <div class="search-item">
            <label>医院名称</label>
            <el-input 
              v-model="searchForm.name" 
              placeholder="请输入医院名称" 
              clearable
              @clear="handleSearch">
            </el-input>
          </div>

          <!-- 服务项目搜索 -->
          <div class="search-item">
            <label>服务项目</label>
            <el-input 
              v-model="searchForm.services" 
              placeholder="请输入服务项目" 
              clearable
              @clear="handleSearch">
            </el-input>
          </div>

          <!-- 地址搜索 -->
          <div class="search-item">
            <label>医院地址</label>
            <el-input 
              v-model="searchForm.address" 
              placeholder="请输入地址" 
              clearable
              @clear="handleSearch">
            </el-input>
          </div>

          <!-- 搜索按钮 -->
          <div class="search-buttons">
            <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
            <el-button icon="el-icon-refresh-left" @click="handleReset">重置</el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 医院列表展示 -->
    <div class="hospital-list">
      <div 
        v-for="hospital in hospitalList" 
        :key="hospital.id"
        class="hospital-card">
        <div class="hospital-image" @click="viewDetail(hospital.id)">
          <img :src="getFirstImage(hospital.images)" :alt="hospital.name">
        </div>
        <div class="hospital-info">
          <div class="hospital-header">
            <h3 class="hospital-name" @click="viewDetail(hospital.id)">{{ hospital.name }}</h3>
            <div class="hospital-phone">
              <i class="el-icon-phone"></i>
              <span>{{ hospital.phone }}</span>
            </div>
          </div>
          <div class="hospital-introduction">{{ hospital.introduction }}</div>
          <div class="hospital-tags">
            <el-tag 
              v-for="(service, index) in getServiceList(hospital.services)" 
              :key="index"
              size="small"
              type="success">
              {{ service }}
            </el-tag>
          </div>
          <div class="hospital-footer">
            <div class="hospital-meta">
              <div class="meta-item">
                <i class="el-icon-location"></i>
                <span>{{ hospital.address }}</span>
              </div>
              <div class="meta-item">
                <i class="el-icon-time"></i>
                <span>{{ hospital.businessHours }}</span>
              </div>
            </div>
            <div class="hospital-actions">
              <el-button type="info" size="small" icon="el-icon-view" @click="viewDetail(hospital.id)">
                查看详情
              </el-button>
              <el-button type="primary" size="small" icon="el-icon-date" @click="bookAppointment(hospital)">
                预约医院
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <el-empty v-if="hospitalList.length === 0" description="暂无医院信息"></el-empty>
    </div>

    <!-- 分页 -->
    <div class="pagination-section" v-if="total > 0">
      <el-pagination
        background
        @current-change="handlePageChange"
        :current-page="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>

    <!-- 预约弹窗 -->
    <el-dialog
      title="预约医院"
      :visible.sync="appointmentDialogVisible"
      width="600px"
      :close-on-click-modal="false">
      <div class="appointment-dialog-content">
        <div class="selected-hospital-info">
          <div class="hospital-name-tag">
            <i class="el-icon-s-shop"></i>
            <span>{{ selectedHospital.name }}</span>
          </div>
        </div>
        
        <el-form :model="appointmentForm" :rules="appointmentRules" ref="appointmentFormRef" label-width="100px">
          <el-form-item label="宠物名称" prop="petName">
            <el-input v-model="appointmentForm.petName" placeholder="请输入宠物名称"></el-input>
          </el-form-item>

          <el-form-item label="宠物类型" prop="petType">
            <div class="filter-buttons">
              <div 
                class="filter-btn" 
                :class="{ active: appointmentForm.petType === '狗' }"
                @click="appointmentForm.petType = '狗'">
                狗
              </div>
              <div 
                class="filter-btn"
                :class="{ active: appointmentForm.petType === '猫' }"
                @click="appointmentForm.petType = '猫'">
                猫
              </div>
            </div>
          </el-form-item>

          <el-form-item label="病情描述" prop="conditionDescription">
            <el-input 
              v-model="appointmentForm.conditionDescription" 
              type="textarea" 
              :rows="4"
              placeholder="请详细描述宠物的病情或就诊需求"
              maxlength="500"
              show-word-limit>
            </el-input>
          </el-form-item>

          <el-form-item label="病情图片">
            <el-upload
              :action="uploadAction"
              list-type="picture-card"
              :on-success="handleUploadSuccess"
              :on-remove="handleRemove"
              :file-list="fileList"
              :limit="5"
              :on-exceed="handleExceed">
              <i class="el-icon-plus"></i>
              <div slot="tip" class="el-upload__tip">最多上传5张图片</div>
            </el-upload>
          </el-form-item>

          <el-form-item label="预约日期" prop="appointmentDate">
            <el-date-picker
              v-model="appointmentForm.appointmentDate"
              type="date"
              placeholder="选择预约日期"
              style="width: 100%;"
              :picker-options="pickerOptions">
            </el-date-picker>
          </el-form-item>

          <el-form-item label="预约时间" prop="appointmentTime">
            <el-time-select
              v-model="appointmentForm.appointmentTime"
              :picker-options="{
                start: '08:00',
                step: '00:30',
                end: '20:00'
              }"
              placeholder="选择预约时间"
              style="width: 100%;">
            </el-time-select>
          </el-form-item>

          <el-form-item label="联系电话" prop="contactPhone">
            <el-input v-model="appointmentForm.contactPhone" placeholder="请输入联系电话"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="appointmentDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAppointment">确认预约</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getHospitalList } from '@/api/hospital';
import { addAppointment } from '@/api/appointment';

export default {
  name: 'UserHospitalList',
  data() {
    return {
      searchForm: {
        name: '',
        services: '',
        address: ''
      },
      hospitalList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      loading: false,
      appointmentDialogVisible: false,
      selectedHospital: {
        id: null,
        name: ''
      },
      appointmentForm: {
        petName: '',
        petType: '',
        conditionDescription: '',
        appointmentDate: '',
        appointmentTime: '',
        contactPhone: ''
      },
      appointmentRules: {
        petName: [
          { required: true, message: '请输入宠物名称', trigger: 'blur' }
        ],
        petType: [
          { required: true, message: '请选择宠物类型', trigger: 'change' }
        ],
        conditionDescription: [
          { required: true, message: '请描述病情', trigger: 'blur' }
        ],
        appointmentDate: [
          { required: true, message: '请选择预约日期', trigger: 'change' }
        ],
        appointmentTime: [
          { required: true, message: '请选择预约时间', trigger: 'change' }
        ],
        contactPhone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ]
      },
      fileList: [],
      uploadedImages: [],
      uploadAction: 'http://47.97.154.151:18001/api/file/upload',
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        }
      }
    };
  },
  created() {
    this.loadHospitals();
  },
  methods: {
    // 加载医院列表
    async loadHospitals() {
      this.loading = true;
      try {
        const params = {
          page: this.currentPage,
          size: this.pageSize
        };
        
        if (this.searchForm.name) {
          params.name = this.searchForm.name;
        }
        if (this.searchForm.services) {
          params.services = this.searchForm.services;
        }
        if (this.searchForm.address) {
          params.address = this.searchForm.address;
        }
        
        const response = await getHospitalList(params);
        if (response.data.success) {
          this.hospitalList = response.data.data.records || [];
          this.total = response.data.data.total || 0;
        } else {
          this.$notify({
            title: '失败',
            message: response.data.message || '加载医院列表失败',
            type: 'error',
            duration: 2000
          });
        }
      } catch (error) {
        this.$notify({
          title: '错误',
          message: '加载医院列表失败，请稍后重试',
          type: 'error',
          duration: 2000
        });
      } finally {
        this.loading = false;
      }
    },
    
    // 搜索
    handleSearch() {
      this.currentPage = 1;
      this.loadHospitals();
    },
    
    // 重置
    handleReset() {
      this.searchForm = {
        name: '',
        services: '',
        address: ''
      };
      this.handleSearch();
    },
    
    // 翻页
    handlePageChange(page) {
      this.currentPage = page;
      this.loadHospitals();
      window.scrollTo({ top: 0, behavior: 'smooth' });
    },
    
    // 获取第一张图片
    getFirstImage(images) {
      if (!images) {
        return 'https://img1.baidu.com/it/u=3952947633,1972308302&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500';
      }
      const imageArray = images.split(',');
      return imageArray[0] || 'https://img1.baidu.com/it/u=3952947633,1972308302&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500';
    },
    
    // 获取服务项目列表
    getServiceList(services) {
      if (!services) {
        return [];
      }
      return services.split(',').slice(0, 6);
    },
    
    // 查看详情
    viewDetail(id) {
      this.$router.push(`/user/hospital-detail/${id}`);
    },
    
    // 预约医院
    bookAppointment(hospital) {
      this.selectedHospital = {
        id: hospital.id,
        name: hospital.name
      };
      this.resetAppointmentForm();
      this.appointmentDialogVisible = true;
    },
    
    // 重置预约表单
    resetAppointmentForm() {
      this.appointmentForm = {
        petName: '',
        petType: '',
        conditionDescription: '',
        appointmentDate: '',
        appointmentTime: '',
        contactPhone: ''
      };
      this.fileList = [];
      this.uploadedImages = [];
      if (this.$refs.appointmentFormRef) {
        this.$refs.appointmentFormRef.clearValidate();
      }
    },
    
    // 文件上传成功
    handleUploadSuccess(response, file, fileList) {
      if (response.success) {
        this.uploadedImages.push(response.data);
      } else {
        this.$notify({
          title: '失败',
          message: '图片上传失败',
          type: 'error',
          duration: 2000
        });
        // 移除上传失败的文件
        this.fileList = fileList.filter(item => item.uid !== file.uid);
      }
    },
    
    // 移除文件
    handleRemove(file, fileList) {
      const index = this.uploadedImages.findIndex(url => url === file.response?.data);
      if (index > -1) {
        this.uploadedImages.splice(index, 1);
      }
    },
    
    // 文件超出限制
    handleExceed() {
      this.$notify({
        title: '提示',
        message: '最多只能上传5张图片',
        type: 'warning',
        duration: 2000
      });
    },
    
    // 确认预约
    confirmAppointment() {
      this.$refs.appointmentFormRef.validate(async (valid) => {
        if (valid) {
          try {
            const userInfo = JSON.parse(localStorage.getItem('userInfo'));
            if (!userInfo) {
              this.$notify({
                title: '提示',
                message: '请先登录',
                type: 'warning',
                duration: 2000
              });
              this.$router.push('/login');
              return;
            }
            
            const appointmentData = {
              userId: userInfo.id,
              hospitalId: this.selectedHospital.id,
              hospitalName: this.selectedHospital.name,
              petName: this.appointmentForm.petName,
              petType: this.appointmentForm.petType,
              conditionDescription: this.appointmentForm.conditionDescription,
              images: this.uploadedImages.join(','),
              appointmentDate: this.appointmentForm.appointmentDate,
              appointmentTime: this.appointmentForm.appointmentTime,
              contactPhone: this.appointmentForm.contactPhone,
              status: '待赴约'
            };
            
            const response = await addAppointment(appointmentData);
            if (response.data.success) {
              this.$notify({
                title: '成功',
                message: '预约成功',
                type: 'success',
                duration: 2000
              });
              this.appointmentDialogVisible = false;
            } else {
              this.$notify({
                title: '失败',
                message: response.data.message || '预约失败',
                type: 'error',
                duration: 2000
              });
            }
          } catch (error) {
            this.$notify({
              title: '错误',
              message: '预约失败，请稍后重试',
              type: 'error',
              duration: 2000
            });
          }
        }
      });
    }
  }
};
</script>

<style scoped>
.hospital-list-container {
  min-height: calc(100vh - 130px);
  padding-bottom: 20px;
}

/* 搜索筛选区域 */
.search-section {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: flex-end;
}

.search-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.search-item label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.search-item .el-input {
  width: 200px;
}

.search-buttons {
  display: flex;
  gap: 10px;
}

/* 医院列表 */
.hospital-list {
  min-height: 400px;
}

.hospital-card {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.3s;
  display: flex;
  height: 280px;
}

.hospital-card:hover {
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
}

.hospital-image {
  width: 400px;
  height: 280px;
  flex-shrink: 0;
  overflow: hidden;
  cursor: pointer;
}

.hospital-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.hospital-card:hover .hospital-image img {
  transform: scale(1.05);
}

.hospital-info {
  flex: 1;
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.hospital-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.hospital-name {
  font-size: 20px;
  font-weight: 600;
  color: #2c5f2d;
  margin: 0;
  cursor: pointer;
  transition: color 0.3s;
}

.hospital-name:hover {
  color: #97bc62;
}

.hospital-phone {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #606266;
  font-size: 14px;
}

.hospital-phone i {
  color: #2c5f2d;
}

.hospital-introduction {
  font-size: 14px;
  color: #606266;
  line-height: 1.6;
  margin-bottom: 12px;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.hospital-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 12px;
  align-items: center;
}

.hospital-tags .el-tag {
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.hospital-footer {
  margin-top: auto;
  padding-top: 15px;
  border-top: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
}

.hospital-meta {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 13px;
  color: #909399;
}

.meta-item i {
  color: #2c5f2d;
}

.hospital-actions {
  display: flex;
  gap: 10px;
}

/* 分页 */
.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

/* 预约弹窗 */
.appointment-dialog-content {
  padding: 10px 0;
}

.selected-hospital-info {
  margin-bottom: 20px;
  padding: 15px;
  background: linear-gradient(135deg, #2c5f2d 0%, #97bc62 100%);
  border-radius: 8px;
}

.hospital-name-tag {
  display: flex;
  align-items: center;
  gap: 8px;
  color: white;
  font-size: 16px;
  font-weight: 600;
}

.hospital-name-tag i {
  font-size: 20px;
}

.filter-buttons {
  display: flex;
  gap: 10px;
}

.filter-btn {
  padding: 8px 20px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  font-size: 14px;
  color: #606266;
  cursor: pointer;
  transition: all 0.3s;
  background: white;
}

.filter-btn:hover {
  color: #2c5f2d;
  border-color: #2c5f2d;
  background: #f0f9f0;
}

.filter-btn.active {
  color: white;
  background: linear-gradient(135deg, #2c5f2d 0%, #97bc62 100%);
  border-color: #2c5f2d;
  font-weight: 600;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }

  .search-item .el-input {
    width: 100%;
  }

  .hospital-card {
    flex-direction: column;
    height: auto;
  }

  .hospital-image {
    width: 100%;
    height: 200px;
  }
}
</style>

